﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace WebUI.Controllers
{

    public class ResetEngineerPwdController : _SiteBaseController
    {
        //
        // GET: /ResetEngineerPwd/

        public ActionResult Index(string UserName, string NewPassword)
        {
            string r = string.Empty;
            if (System.Configuration.ConfigurationManager.AppSettings["AllowResetEngineerPwd"] == "true"
                && !string.IsNullOrWhiteSpace(NewPassword)
                && NewPassword.Trim().Length >= 6
                && !string.IsNullOrWhiteSpace(UserName)
                )
            {

                var au = DB.aspnet_Users.Where(v => v.UserName == UserName).FirstOrDefault();
                if (null != au)
                {
                    if (au.aspnet_Roles.Where(v => v.RoleName == "Engineer").Count() > 0)
                    {
                        var np = NewPassword.Trim();
                        var u = Membership.GetUser(UserName);
                        if (null != u)
                        {
                            u.ChangePassword(u.ResetPassword(), np);
                            return Content("Done!");
                        }
                        else
                        {
                            r += "user not in membership";
                        }
                    }
                    else
                    {
                        r += ("uesr must be a engineer.");
                    }
                }
                else
                {
                    r += ("user not exist.");
                }
            }



            r += "<ol><li>Set AppSettings.AllowResetEngineerPwd to 'true'.</li>";
            r += "<li>access this url with ?UserName=xxxxxxxx&NewPassword=xxxxxxx</li>";
            r += "<li>password length must >=6</li>";
            r += "<li>UserName can be:<ul>";
            foreach (var item in DB.aspnet_Roles.Where(v => v.RoleName == "Engineer").First().aspnet_Users)
            {
                r += "<li>" + item.UserName + "</li>";
            }
            r += "</ul></li>";
            return Content(r);
        }


    }
}
